package cn.dubito.seller.service;

import cn.dubito.entity.VerificationOrder;
import cn.dubito.seller.enums.ChanEnum;
import cn.dubito.seller.repository.VerificationRepository;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liliang
 * @description: 对账服务
 * @date 2018/5/29.
 */
@Service
public class VerifyService {

    @Value("${verification.rootDir:/Users/liliang/Downloads/verification}")
    private String rootDir;

    @Autowired
    private VerificationRepository verificationRepository;

    /**
     * 时间格式化
     */
    private static final String DAY_FORMAT = "yyyy-MM-dd";
    /**
     * 换行符
     */
    private static final String END_LINE = System.getProperty("line.separator", "\n");

    /**
     * 生成渠道的对账文件
     *
     * @param chanId 渠道 ID
     * @param day    时间
     * @return 对账文件
     */
    public File makeVerificationFile(String chanId, Date day) {
        File path = getPath(rootDir, chanId, day);
        if (path.exists()) {
            return path;
        }
        try {
            path.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> orders = verificationRepository.queryVerificationOrders(chanId, day, DateUtils.addDays(day, 1));
        String content = String.join(END_LINE, orders);
        FileUtil.writeAsString(path, content);
        return path;
    }

    public List<String> verifyOrder(String chanId, Date day) {

        List<String> errors = new ArrayList<>();
        List<String> excessOrder = verificationRepository.queryExcessOrder(chanId, day, DateUtils.addDays(day, 1));
        List<String> missOrder = verificationRepository.queryMissOrder(chanId, day, DateUtils.addDays(day, 1));
        List<String> different = verificationRepository.queryDifferentOrder(chanId, day, DateUtils.addDays(day, 1));
        errors.add("长款订单号:" + String.join(",", excessOrder));
        errors.add("漏单订单号:" + String.join(",", missOrder));
        errors.add("不一致订单号:" + String.join(",", different));

        return errors;
    }

    /**
     * 获取对账文件路径
     *
     * @param chanId 渠道 ID
     * @param day    时间
     * @return 文件路径
     */
    private File getPath(String rootDir, String chanId, Date day) {
        String name = DateFormatUtils.format(day, DAY_FORMAT) + "-" + chanId + ".txt";
        File file = new File(rootDir);
        if (!file.exists()) {
            file.mkdir();
        }
        return Paths.get(rootDir, name).toFile();
    }

    /**
     * 按照字符串顺序解析对账订单
     *
     * @param line
     * @return
     */
    public static VerificationOrder parseLine(String line) {
        if (StringUtils.isEmpty(line)) {
            throw new RuntimeException("不可以为空");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        VerificationOrder order = new VerificationOrder();
        String[] props = line.split("\\|");
        order.setOrderId(props[5]);
        order.setOuterOrderId(props[0]);
        order.setChanId(props[1]);
        order.setChanUserId(props[3]);
        order.setOrderType(props[4]);
        order.setProductId(props[2]);
        order.setAmount(new BigDecimal(props[6]));
        try {
            order.setCreateAt(simpleDateFormat.parse(props[7]));
        } catch (ParseException e) {
            throw new RuntimeException("时间转换错误");
        }
        return order;
    }

    /**
     * 保存聚到订单数据
     *
     * @param chanId
     * @param day
     */
    public void saveChanOrder(String chanId, Date day) {
        ChanEnum conf = ChanEnum.getByChanId(chanId);
        File file = getPath(conf.getRootDir(), chanId, day);
        if (!file.exists()) {
            return;
        }
        String content = null;
        try {
            content = FileUtil.readAsString(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] lines = content.split(END_LINE);
        List<VerificationOrder> orders = new ArrayList<>();
        for (String line : lines) {
            orders.add(parseLine(line));
        }
        verificationRepository.save(orders);
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("line.separator"));
    }
}
